<template>
  <div class="reservation-form">
    <a-card :title="formTitle" class="form-card">
      <a-form
        :model="formData"
        :rules="rules"
        @finish="onSubmit"
        layout="vertical"
      >        <!-- 预约类型选择 -->
        <a-form-item label="预约类型" name="reservationType">
          <a-radio-group v-model:value="formData.reservationType" @change="onTypeChange">
            <a-radio :value="1" :disabled="isCoach">健身场馆预约</a-radio>
            <a-radio :value="2" :disabled="isFitnessEnthusiast">健身教练场地预约</a-radio>
          </a-radio-group>
          <div class="type-hint" v-if="isCoach">
            <a-alert 
              message="作为健身教练，您只能进行场地预约" 
              type="info" 
              show-icon 
              style="margin-top: 8px"
            />
          </div>
          <div class="type-hint" v-else-if="isFitnessEnthusiast">
            <a-alert 
              message="作为健身爱好者，建议选择健身场馆预约" 
              type="info" 
              show-icon 
              style="margin-top: 8px"
            />
          </div>
        </a-form-item>

        <!-- 场馆选择 -->
        <a-form-item label="选择场馆" name="gymId">
          <a-select
            v-model:value="formData.gymId"
            placeholder="请选择场馆"
            @change="onGymChange"
            show-search
            :filter-option="filterGymOption"
          >
            <a-select-option v-for="gym in gyms" :key="gym.gymId" :value="gym.gymId">
              {{ gym.name }} - {{ gym.area }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 预约日期 -->
        <a-form-item label="预约日期" name="reservationDate">
          <a-date-picker
            v-model:value="formData.reservationDate"
            placeholder="选择预约日期"
            :disabled-date="disabledDate"
            @change="onDateChange"
            style="width: 100%"
          />
        </a-form-item>

        <!-- 预约时段 -->
        <a-form-item label="预约时段" name="timeSlot">
          <a-select
            v-model:value="formData.timeSlot"
            placeholder="请选择时间段"
            :loading="loadingSlots"
          >
            <a-select-option v-for="slot in availableSlots" :key="slot" :value="slot">
              {{ slot }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <!-- 教练预约专用字段 -->
        <template v-if="formData.reservationType === 2">
          <!-- 区域类型 -->
          <a-form-item label="预约区域" name="areaType">
            <a-select v-model:value="formData.areaType" placeholder="请选择预约区域">
              <a-select-option value="无器械运动区">无器械运动区</a-select-option>
              <a-select-option value="力量训练区">力量训练区</a-select-option>
              <a-select-option value="有氧运动区">有氧运动区</a-select-option>
              <a-select-option value="瑜伽室">瑜伽室</a-select-option>
              <a-select-option value="舞蹈室">舞蹈室</a-select-option>
              <a-select-option value="私教室">私教室</a-select-option>
            </a-select>
          </a-form-item>

          <!-- 使用说明 -->
          <a-form-item label="使用说明" name="description">
            <a-textarea
              v-model:value="formData.description"
              placeholder="请描述您的使用计划和需求"
              :rows="4"
              :maxlength="200"
              show-count
            />
          </a-form-item>
        </template>

        <!-- 提交按钮 -->
        <a-form-item>
          <a-space>
            <a-button type="primary" html-type="submit" :loading="submitting">
              提交预约
            </a-button>
            <a-button @click="resetForm">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import http from '@/utils/http'
import dayjs from 'dayjs'

const router = useRouter()

// 获取当前用户信息
const getCurrentUser = () => {
  try {
    return JSON.parse(localStorage.getItem('user') || '{}')
  } catch (error) {
    console.error('解析用户信息失败:', error)
    return {}
  }
}

const currentUser = ref(getCurrentUser())

// 响应式数据
const formData = reactive({
  reservationType: 1,
  gymId: null,
  reservationDate: null,
  timeSlot: null,
  areaType: null,
  description: ''
})

const gyms = ref([])
const availableSlots = ref([])
const submitting = ref(false)
const loadingSlots = ref(false)

// 计算属性
const formTitle = computed(() => {
  return formData.reservationType === 1 ? '健身场馆预约' : '健身教练场地预约'
})

// 用户角色判断
const isCoach = computed(() => currentUser.value?.role === 2)
const isFitnessEnthusiast = computed(() => currentUser.value?.role === 1)

// 根据用户角色设置默认预约类型
const initReservationType = () => {
  if (isCoach.value) {
    formData.reservationType = 2 // 教练默认为场地预约
  } else {
    formData.reservationType = 1 // 其他用户默认为健身预约
  }
}

// 表单验证规则
const rules = {
  reservationType: [
    { required: true, message: '请选择预约类型', trigger: 'change' }
  ],
  gymId: [
    { required: true, message: '请选择场馆', trigger: 'change' }
  ],
  reservationDate: [
    { required: true, message: '请选择预约日期', trigger: 'change' }
  ],
  timeSlot: [
    { required: true, message: '请选择预约时段', trigger: 'change' }
  ],
  areaType: [
    { required: true, message: '请选择预约区域', trigger: 'change', type: 'string' }
  ]
}

// 方法
const loadGyms = async () => {
  try {
    const response = await http.get('/v1/gym/selectActiveGyms')
    if (response.data.code === 2000) {
      gyms.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载场馆列表失败:', error)
    message.error('加载场馆列表失败')
  }
}

const loadAvailableSlots = async () => {
  if (!formData.gymId || !formData.reservationDate) {
    availableSlots.value = []
    return
  }

  loadingSlots.value = true
  try {
    const dateStr = dayjs(formData.reservationDate).format('YYYY-MM-DD')
    const response = await http.get('/v1/reservation/available-slots', {
      params: {
        gymId: formData.gymId,
        date: dateStr
      }
    })
    
    if (response.data.code === 2000) {
      availableSlots.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载可用时间段失败:', error)
    message.error('加载可用时间段失败')
  } finally {
    loadingSlots.value = false
  }
}

const onTypeChange = () => {
  // 清空相关字段
  formData.areaType = null
  formData.description = ''
}

const onGymChange = () => {
  // 清空时间相关字段
  formData.timeSlot = null
  loadAvailableSlots()
}

const onDateChange = () => {
  // 清空时间段
  formData.timeSlot = null
  loadAvailableSlots()
}

const disabledDate = (current) => {
  // 禁用今天之前的日期
  return current && current.isBefore(dayjs(), 'day')
}

const filterGymOption = (input, option) => {
  return option.children.toLowerCase().includes(input.toLowerCase())
}

const onSubmit = async (values) => {
  submitting.value = true
  try {
    const reservationData = {
      ...values,
      reservationDate: dayjs(values.reservationDate).format('YYYY-MM-DD')
    }

    // 如果是健身爱好者预约，清空教练专用字段
    if (reservationData.reservationType === 1) {
      delete reservationData.areaType
      delete reservationData.description
    }

    const response = await http.post('/v1/reservation/create', reservationData)
    
    if (response.data.code === 2000) {
      message.success('预约提交成功！我们已为您创建聊天会话，场馆管理员会尽快回复。')
      // 跳转到聊天页面或预约列表
      router.push('/chat')
    } else {
      message.error(response.data.msg || '预约失败')
    }
  } catch (error) {
    console.error('提交预约失败:', error)
    message.error('提交预约失败，请重试')
  } finally {
    submitting.value = false
  }
}

const resetForm = () => {
  Object.assign(formData, {
    reservationType: 1,
    gymId: null,
    reservationDate: null,
    timeSlot: null,
    areaType: null,
    description: ''
  })
  availableSlots.value = []
}

// 监听器
watch([() => formData.gymId, () => formData.reservationDate], () => {
  loadAvailableSlots()
})

// 生命周期
onMounted(() => {
  initReservationType()
  loadGyms()
})
</script>

<style scoped>
.reservation-form {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.form-card {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.ant-radio-group {
  width: 100%;
}

.ant-radio-wrapper {
  margin-right: 20px;
}

@media (max-width: 768px) {
  .reservation-form {
    padding: 10px;
  }
  
  .ant-radio-wrapper {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
